import React, { useEffect, useState } from 'react';
import { Pagination } from '@teamix/ui';
import { Footer } from '@alife/devops-ui';

/**
 * 宽度大于692时，分页器完整
 * 宽度大于508时，分页器有跳转
 * 宽度小于508时，只有简单页数
 * ************************
 * 当footer的left有组件时，设置leftWidth， 默认360px
 */
export default (props) => {
  const [simple, setSimple] = useState(false);
  const [jump, setJump] = useState(true);
  const {
    onChange,
    current,
    total,
    leftWidth = 0,
    noBorderTop = false,
    footerProps,
    ...others
  } = props;

  const onResize = () => {
    const dom = document.querySelector('.teamix-layout-footer');
    if (dom) {
      const { width } = dom.getBoundingClientRect();
      if (width < 790 + leftWidth) {
        setSimple(true);
      } else {
        setSimple(false);
      }
      if (width < 508 + leftWidth) {
        setJump(false);
      } else {
        setJump(true);
      }
      if (width < 284 + leftWidth) {
        document.querySelector('.teamix-layout-footer-left').style.visibility = 'hidden';
        document.querySelector('.teamix-layout-footer-left').style.width = 0;
      } else {
        document.querySelector('.teamix-layout-footer-left').style.visibility = 'visible';
        document.querySelector('.teamix-layout-footer-left').style.width = 'unset';
      }
    } else {
      setTimeout(() => {
        onResize();
      }, 17);
    }
  };

  useEffect(() => {
    onResize();
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
    };
  }, []);

  useEffect(() => {
    onResize();
    window.removeEventListener('resize', onResize);
    window.addEventListener('resize', onResize);
  }, [leftWidth]);

  if (!total) return null;
  if (!props.onPageSizeChange) {
    return (
      <Footer noBorderTop={noBorderTop} {...footerProps}>
        <Pagination {...props} />
      </Footer>
    );
  }
  const useProps = {};
  if (current) {
    useProps.current = current;
  }

  const simpleControlProps = simple
    ? {}
    : {
        showJump: true,
        pageSizeList: [10, 20, 50],
        pageSizeSelector: 'dropdown',
      };

  const handleChange = (cur) => {
    onChange(cur);
  };

  return (
    <Footer noBorderTop={noBorderTop} {...footerProps}>
      <Pagination
        onChange={handleChange}
        total={total}
        {...simpleControlProps}
        {...useProps}
        {...others}
        showJump={jump}
      />
    </Footer>
  );
};
